#--
# Copyright (c) 2007 Maximilian Ott
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#++
# == Schema Information
# Schema version: 13
#
# Table name: documents
#
#  id           :integer(11)   not null, primary key
#  document_id  :string(255)   
#  version_id   :string(255)   
#  reference_id :integer(11)   
#  file_name    :string(255)   
#  content_type :string(255)   
#  position     :integer(11)   
#  type         :string(255)   
#  created_at   :datetime      
#

require 'uuidtools'

#
# This model holds all the information about uploaded
# documents. The model keeps track of versions.
#
class Document < ActiveRecord::Base
#  acts_as_list :scope => 'reference_id = #{reference_id} AND type = \'#{type}\''
   acts_as_list :scope => 'reference_id = #{reference_id} AND type = \'#{type}\''
#  belongs_to :student

  EXTENSIONS = {
    'plain' => 'txt',
    'vnd.ms-powerpoint' => 'ppt',
    'vnd.ms-excel' => 'csv',
    'vnd.ms-word' => 'doc',
    'vnd.google-earth.kml+xml' => 'kml'
  }
  REPOSITORY_URL = '/docs/'
  REPOSITORY_PATH = "public#{REPOSITORY_URL}"
  
  after_save :dump_meta
  
  
  # 
  # Initialize a document from an upload field.
  #
  # Note, this only creates the document, but doe NOT save it.
  #
  def self.init_from_upload(upload_field, options = {})
    doc = new(options)
    doc.content = upload_field
    doc
  end
  
  def name
    ct = self.created_at
    "V#{self.position}: #{ct ? ct.asctime : 'unknown'}"
  end
  
  def url(path = REPOSITORY_URL)
    path + self.file_name
  end
  
  def content=(io)
    if io.nil? || io.kind_of?(String)
      raise 'Illegal file name.'
    end

    if (io.respond_to?(:content_type))
      content_type = io.content_type
      raise 'Missing content_type' if content_type.nil?
      self.content_type = content_type.to_s.chomp
      ext = self.content_type.split('/')[-1] || "data"
      puts ">>>>> ContentTYPE #{self.content_type} : #{ext}"
      if EXTENSIONS.has_key?(ext)
        ext = EXTENSIONS[ext]
      end
    
      unless (fn = self.document_id)
        fn = self.document_id = UUID.random_create.to_s
      end
      fname = self.file_name = fn + '.' + ext
      f = File.new(REPOSITORY_PATH + fname, "w")
      f.binmode
      f.write io.read
      f.close
      self.upload_name = io.original_filename
    else
      raise "Unknown type of document content '#{io.class}'"
    end
  end
  
  
  # Write Meta information to file in case we loose the database. The meta
  # file has the same name as the associated document, but with a '.meta'
  # extension.
  #
  def dump_meta
    fm = File.new(REPOSITORY_PATH + self.document_id + '.meta', "w")
    fm.write self.to_yaml
    fm.close
  end
end
